#!/usr/bin/env python

# This file is part of the Possumcam project 
# at http://code.google.com/p/possumcam/
#
# Released under the GPLv3 at http://www.gnu.org/copyleft/gpl.html
# Designed for Kenneth Lavrsen's motion project at
# http://www.lavrsen.dk/twiki/bin/view/Motion
#
# Copyright 2008 by Jackson Yee (jackson@gotpossum.com)

import os
import subprocess
import datetime
import time
import gc

from lumenn.files import FileList, FileInfo
from lumenn.db import DB, ListAdapter
import lumenn.log as log

execfile('webserver.config')

db					=	DB( 'filesdb' )
fileregexp	= '.*\.(avi|mov|mp4|asf|wmv)$'
log.SetLog( log.FileLog( 'rotate.log' ) )

# =====================================================================
def SaveToDB(filelist, dirname):
	if len(filelist) > 2500:
		db.Save(filelist.ls)
		
		ls	=	[]
		
		#for f in filelist:			
		
		filelist.Clear()
		gc.collect()

# =====================================================================
def ScanDir(dirname):
	log.Log(log.ACTION, 'Scanning directory %s for video files...' % dirname)
	
	filelist	=	FileList()
	
	db.Delete( 
		FileInfo, 
		"WHERE dirname LIKE '%s%%'" % dirname,
	)
	
	filelist.Load(dirname, 
		fileregexp, 
		None, 
		True,
		SaveToDB,
	)
	
	db.Save(filelist.ls)
	
	log.Log(log.ACTION, 'Scan complete: %i videos found\n' % len(filelist) )

# =====================================================================
def DeleteOldest(dirname, sizelimit):
	ScanDir(dirname)
	
	ls	=	ListAdapter(db, FileInfo)
	ls.SetFilter('ORDER BY modtime')
	
	sizedeleted	=	0
	
	for v in ls:
		if sizedeleted > sizelimit:
			return
		
		try:
			os.remove( v.GetPath() )
			sizedeleted += v.size / 1024.0
			log.Log(log.ACTION, 'Removed %s and freed %iMiB\n' % (v.GetPath(), v.size / float(1024 * 1024) ) )
			db.Delete(v)
		except Exception, e:
			log.Log(log.ERROR, 'Could not remove %s: %s' % (v.GetPath(), e) )

# =====================================================================
def Run():
	gb	= 1024 * 1024
	limit	=	2 * gb
		
	try:	
		
		log.Log(log.ACTION, 'Running video rotation at %s\n' % datetime.datetime.now().strftime('%x %X') )
		
		output = subprocess.Popen(["df", "-l"], 
			stdout = subprocess.PIPE
		).communicate()[0]
		
		freespace	=	0
		
		for l in output.split('\n'):
			parts = l.split()
			
			if len(parts) > 5:
				if parts[5] ==  videosmount:
					freespace = float(parts[3])
		
		log.Log(log.ACTION, 'Free space:\t%.2fG\n' % (freespace / gb) )
		log.Log(log.ACTION, 'Limit:\t\t%.2fG\n' % (limit / gb) )
			
		if freespace < limit:
			DeleteOldest(videosdir, limit - freespace)
		
		log.Log(log.ACTION, 'Finished video rotation at %s\n\n' % datetime.datetime.now().strftime('%x %X') )
	except Exception, e:
		log.Log(log.ACTION, 'Problem running script: %s\n\n' % e)
	
	gc.collect()
	log.Log(log.ACTION, '------------------------------------------------\n\n')

# =====================================================================
if __name__ == '__main__':
	try:
		Run()
	except Exception, e:
		print 'Exception caught. Exiting: ', e
		

